package com.example.myapplication.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.myapplication.R;
import com.example.myapplication.bean.Course;
import com.example.myapplication.bean.Student;

import java.util.List;

public class CourseAdapter extends BaseAdapter {
    private List<Course> mList;

    // 布局填充器
    private LayoutInflater mLayoutInflater;

    // 构造方法，初始化课程列表和布局填充器
    public CourseAdapter(List<Course> list, Context context){
        mList = list;
        mLayoutInflater = LayoutInflater.from(context);
    }

    // 更新课程数据
    public void updateData(List<Course> list) {
        mList.clear();
        mList = list;
        notifyDataSetChanged();
    }

    // 获取列表项数量
    @Override
    public int getCount() {
        return mList.size();
    }

    // 获取指定位置的课程
    @Override
    public Course getItem(int position) {
        return mList.get(position);
    }

    // 获取指定位置的课程ID
    @Override
    public long getItemId(int position) {
        return position;
    }

    // 获取视图
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CourseAdapter.ViewHolder viewHolder;
        if (convertView == null) {
            // 如果视图为空，创建新的视图
            viewHolder = new CourseAdapter.ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.course_item, null);
            // 绑定视图中的文本控件
            viewHolder.idText = convertView.findViewById(R.id._id);
            viewHolder.nameText = convertView.findViewById(R.id.course_name);
            viewHolder.codeText = convertView.findViewById(R.id.course_code);
            viewHolder.teacherText = convertView.findViewById(R.id.course_teacher);
            viewHolder.hoursText = convertView.findViewById(R.id.learning_hours);
            // 将ViewHolder与convertView进行绑定
            convertView.setTag(viewHolder);
        } else {
            // 如果视图不为空，获取已存在的ViewHolder
            viewHolder = (CourseAdapter.ViewHolder) convertView.getTag();
        }
        // 获取当前位置的课程对象
        Course course = getItem(position);
        if (course != null) {
            // 将课程对象存储到convertView中
            convertView.setTag(R.integer.friend_tag, course);
            // 设置文本控件显示的课程信息
            viewHolder.idText.setText(String.valueOf(course.getCourse_id()));
            viewHolder.nameText.setText(course.getCourse_name());
            viewHolder.codeText.setText(course.getCourse_code());
            viewHolder.teacherText.setText(course.getCourse_teacher());
            viewHolder.hoursText.setText(course.getLearning_hours());
        }
        return convertView;
    }

    // 静态内部类ViewHolder，用于存储视图中的控件
    private static class ViewHolder {
        TextView idText;
        TextView nameText;
        TextView codeText;
        TextView teacherText;
        TextView hoursText;
    }
}
